<template>
  <div class="app-container">
    <div>
      <el-form :inline="true">
        <el-form-item label="姓名">
          <el-input v-model="userQuery.name" style="width:150px" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input  v-model="userQuery.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            placeholder="请选择状态"
            style="width: 150px"
            v-model="userQuery.status" >
            <el-option label="禁用" value="0"></el-option>
            <el-option label="可用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建开始时间">
          <el-date-picker
            v-model="userQuery.gmtCreateBegin"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建结束时间">
          <el-date-picker
            v-model="userQuery.gmtCreateEnd"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="selectByPage()">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="refreshSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-button type="success" icon="el-icon-plus" size="mini" @click="showAddDialog()" :disabled="!$hasBP('rbac:user:add')">添加</el-button>
    <el-button type="danger"  icon="el-icon-delete" size="mini" @click="deleteAll()">批量删除</el-button>
    <el-button type="primary"  icon="el-icon-download" size="mini" @click="exportData()">导出</el-button>
    <el-button type="primary"  icon="el-icon-upload" size="mini" @click="importData()">导入</el-button>
    <el-table :data="list" @selection-change="handleSelectionChange" fit border style="width: 100%" >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column fixed prop="id" label="ID"> </el-table-column>
      <el-table-column prop="name" label="姓名"> </el-table-column>
      <el-table-column prop="trueName" label="真实名字"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="phone" label="手机"> </el-table-column>
      <el-table-column prop="avatar" label="头像" width="100">
        <template slot-scope="scope">
          <el-image :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <!-- 'v-model' directives require the attribute value which is valid as LHS.
            v-model的值必须是一个数据类型，而不是一个条件值或者计算值
           -->
          <el-switch
            v-model="scope.row.status === 1"
            @change="switchStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            title="修改"
            @click="showUpdateDialog(scope.row.id)"
            ></el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            title="删除"
            :disabled="!$hasBP('rbac:user:delete')"
            @click="deleteById(scope.row.id)"
            ></el-button
          >
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-setting"
            title="角色分配"
            @click="showAssignedRoleDialog(scope.row)"
            ></el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="selectByPage"
      :current-page="page"
      :total="total"
      :page-size="limit"
      layout="total, prev, pager, next"
    >
    </el-pagination>

    <!-- 添加、修改的dialog -->
    <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
      <el-form ref="form" :model="user" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item label="真实名字">
          <el-input v-model="user.trueName"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>
        <el-form-item label="用户头像">
          <!-- 头像缩略图 -->
          <pan-thumb :image="image" />
          <!-- 文件上传按钮 -->
          <el-button
            type="primary"
            icon="el-icon-upload"
            style="position: absolute; bottom: 15px; margin-left: 40px"
            @click="imagecropperShow = true"
          >
            Change Avatar
          </el-button>
          <!-- 上传头像 
            v-show="imagecropperShow"控制是否弹出上传组件
            :key 类似id，唯一标识
            url:后台上传的地址
            @close="close" 关闭上传组件
            @crop-upload-success 上传成功后的回调 
            <input type="file" name="file"/>
            -->
          <image-cropper
            v-show="imagecropperShow"
            :key="imagecropperKey"
            :width="300"
            :height="300"
            url="/oss/upload/uploadImage"
            field="file"
            lang-type="en"
            @close="close"
            @crop-upload-success="cropSuccess"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addOrUpdate">提交</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible" width="40%">
      <el-form ref="form" :model="user" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="user.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox-group v-model="assignedRoleIdList">
            <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{role.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="assignRole">保存</el-button>
          <el-button  @click="dialogRoleVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>    

     <el-dialog title="导入" :visible.sync="dialogImportVisible" width="40%">
      <el-form label-width="170px">
        <el-form-item label="文件">
          <el-upload
            class="upload-demo"
            action="/rbac/user/importData"
            :on-success="onUploadSuccess"
            :headers="headers"
            :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过500kb</div>
          </el-upload>

        </el-form-item>
      </el-form>
     </el-dialog>
  </div>
</template>
  
<script>
//引入user.js
import userApi from "@/api/rbac/user";
import roleApi from "@/api/rbac/role";
import ImageCropper from "@/components/ImageCropper";
import PanThumb from "@/components/PanThumb";
import { getToken } from '@/utils/auth'

export default {
  name: "",
  components: { ImageCropper, PanThumb },
  data() {
    return {
      list: null, //表格对应的数据
      page: 1, //当前页
      limit: 5, //每页有多少条
      total: 0, //总记录数

      //添加、编辑相关代码
      dialogVisible: false, //添加、修改dialog
      user: {}, //添加、修改对应封装的user对象
      //图片上传相关
      imagecropperShow: false,
      imagecropperKey: 0,
      image: "https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191",

      //添加角色相关
      dialogRoleVisible: false,
      roleList: [],
      assignedRoleIdList: [],

      //批量删除
      deleteIds: [],
      userQuery: {},

      dialogImportVisible: false,
      headers: {
        Token: getToken()
      }
    };
  },
  created() {
    this.selectByPage(this.page);
    /*userApi.selectByPage(this.page, this.limit).then((response) => {
      console.log(response);
      this.list = response.data.list;
      this.total = response.data.total;
    });*/
  },
  methods: {
    selectByPage(page = 1) {
      console.log(this.userQuery);
      this.page = page;
      userApi.selectByPage(this.page, this.limit, this.userQuery).then((jsonResult) => {
        console.log(jsonResult);
        this.list = jsonResult.data.list;
        //Invalid prop: type check failed for prop "total". Expected Number with value 8, got String with value "8".
        //把long类型转换成Number类型
        this.total = jsonResult.data.total - 0;
      });
    },
    refreshSearch() {
      this.userQuery = {}
    },
    deleteById(id) {
      //弹出确认删除的提示框
      this.$confirm("您确认要删除么?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }).then(() => {
        userApi.deleteById(id).then((jsonResult) => {
          if (jsonResult.ok) {
            this.$message({
              type: "success",
              message: jsonResult.msg,
            });
            //删除成功之后，查询最新的数据
            this.selectByPage();
          } else {
            this.$message({
              type: "error",
              message: jsonResult.msg,
            });
          }
        });
      });
    },
    handleSelectionChange(selections) {
      console.log(selections);
      this.deleteIds = selections.map(item => item.id);
      console.log(this.deleteIds);
    },
    deleteAll() {
      if(this.deleteIds.length == 0) {
        this.$message({
          type: "error",
          message: '请选择要删除的信息',
        });
        return;
      } 

      this.$confirm("您确认要删除么?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }).then(() => {
        userApi.deleteAll(this.deleteIds.join(',')).then((jsonResult) => {
          if (jsonResult.ok) {
            this.$message({
              type: "success",
              message: jsonResult.msg,
            });
            //删除成功之后，查询最新的数据
            this.selectByPage();
          } else {
            this.$message({
              type: "error",
              message: jsonResult.msg,
            });
          }
        });
      });
    },
    switchStatus(row) {
      //对当前是status状态取反
      row.status = row.status === 1 ? 0 : 1;
      userApi.updateStatus(row.id, row.status).then((jsonResult) => {
        if (jsonResult.ok) {
          this.$message({
            type: "success",
            message: jsonResult.msg,
          });
        } else {
          this.$message({
            type: "error",
            message: jsonResult.msg,
          });
        }
      });
    },
    //添加、编辑相关代码
    showAddDialog() {
      this.dialogVisible = true;
      this.user = {};
      this.image =
        "https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191";
    },
    showUpdateDialog(id) {
      this.dialogVisible = true;
      this.user = {};
      this.image =
        "https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191";
      userApi.selectById(id).then((jsonResult) => {
        this.user = jsonResult.data;
        console.log(this.user.avatar);
        if (this.user.avatar) {
          this.image = this.user.avatar;
        } 
      });
    },
    addOrUpdate() {
      if (!this.user.id) {
        userApi.add(this.user).then((jsonResult) => {
          if (jsonResult.ok) {
            this.$message({
              type: "success",
              message: jsonResult.msg,
            });
            //关闭弹出框
            this.dialogVisible = false;
            this.selectByPage();
          } else {
            this.$message({
              type: "error",
              message: jsonResult.msg,
            });
          }
        });
      } else {
        userApi.update(this.user).then((jsonResult) => {
          if (jsonResult.ok) {
            this.$message({
              type: "success",
              message: jsonResult.msg,
            });
            this.dialogVisible = false;
            this.selectByPage();
          } else {
            this.$message({
              type: "error",
              message: jsonResult.msg,
            });
          }
        });
      }
    },
    showAssignedRoleDialog(row) {
      this.user = row;
      roleApi.selectAssignedRole(row.id).then((jsonResult) => {
        this.roleList = jsonResult.data.roleList;
        this.assignedRoleIdList = jsonResult.data.assignedRoleIdList;
        this.dialogRoleVisible = true;
      });
    },
    assignRole() {
      let roleIds = this.assignedRoleIdList.join(',');
      roleApi.assignRole(this.user.id, roleIds).then((jsonResult) => {
        if (jsonResult.ok) {
          this.$message({
              type: "success",
              message: jsonResult.msg,
            });
            this.dialogRoleVisible = false;
        }
      });
    },
    cropSuccess(resData) {
      console.log(resData);
      this.imagecropperShow = false;
      this.imagecropperKey = this.imagecropperKey + 1;
      this.user.avatar = resData;
      this.image = resData;
    },
    close() {
      this.imagecropperShow = false;
    },
    exportData() {
      //vue+axios+token
      userApi.exportData().then((res) => {
        let blob = new Blob([res], { type: "application/xlsx" });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "员工列表.xlsx"; // 重命名文件
        link.click();
        URL.revokeObjectURL(url);
      });
    },
    importData() {
      this.dialogImportVisible = true;
    },
    onUploadSuccess() {
      this.dialogImportVisible = false;
      this.selectByPage();
    }
  },
};
</script>
 
<style scoped>
</style>